package com.gduf.lsm.service;

import cn.hutool.core.util.ObjectUtil;
import com.gduf.lsm.common.enums.ResultCodeEnum;
import com.gduf.lsm.entity.Category;
import com.gduf.lsm.exception.CustomException;
import com.gduf.lsm.mapper.CategoryMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author lsm
 * @Data
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增
     * @param category
     */
    public void add(Category category) {
        //根据名字查询是否为空
        if(category.getName()==null){
            throw new CustomException(ResultCodeEnum.CATEGORY_NULL_ERROR);
        }
        //根据名字查询是否名称重复
        Category dbCategory = categoryMapper.selectByName(category.getName());
        //判断咨询分类名是否存在
        if (ObjectUtil.isNotNull(dbCategory)) {
            throw new CustomException(ResultCodeEnum.CATEGORY_EXIST_ERROR);
        }
        categoryMapper.insert(category);
    }

    /**
     * 删除单个
     * @param id
     */
    public void deleteById(Integer id) {
        categoryMapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            categoryMapper.deleteById(id);
        }
    }

    /**
     * 修改
     * @param category
     */
    public void updateById(Category category) {
        //判断是否存在此分类名，存在则分类名不可修改
        Category c=categoryMapper.selectByName(category.getName());
        if (ObjectUtil.isNotNull(c)){
            throw new CustomException(ResultCodeEnum.CATEGORY_EXIST_ERROR);
        }
        categoryMapper.updateById(category);
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Category selectById(Integer id) {
        return categoryMapper.selectById(id);
    }

    /**
     * 查询所有
     * @param category
     * @return
     */
    public List<Category> selectAll(Category category) {
        return categoryMapper.selectAll(category);
    }

    /**
     * 分页查询
     * @param category
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<Category> selectPage(Category category, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> list = categoryMapper.selectAll(category);
        return PageInfo.of(list);
    }

}
